package http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class HttpRequestData {

    public static void main(String[] args) {
        HttpURLConnection connection = null;
        OutputStream out = null;
        BufferedReader reader = null;
        try {
            URL url = new URL("https://arp.caas.cn/pbs/api/token/create");
            connection = (HttpURLConnection) url.openConnection();
            //设置输出模式 POST 要单独输出参数 要设置为 true
            connection.setDoOutput(true);
            //从连接中读取返回值
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false); //post 不能使用 cache
            connection.setInstanceFollowRedirects(true); //设置自动重定向
            //设置 content-type
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 开启连接
            // 注意： connection.getOutputStream 会隐含的进行 connect() 调用。
            connection.connect();
            out = connection.getOutputStream();
            //参数
            String content = "appCode=" + URLEncoder.encode("72e6722920fc11ecbe05fa163eaca69b", "UTF-8");
            //发送参数
            out.write(content.getBytes());
            out.flush();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            System.out.println(stringBuilder.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

}
